/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import entity.Contact;
import entity.Event;
import entity.EventComment;
import entity.Invitation;
import entity.enumeration.EventStatus;
import entity.enumeration.InvitationStatus;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.net.ssl.SSLEngineResult.Status;
import javax.servlet.http.HttpSession;
import manager.ContactManager;
import manager.EventCommentManager;
import manager.EventManager;
import manager.InvitationManager;
import utils.HashGenerator;

/**
 * @author Stefan Martinov <stefan.martinov@gmail.com>
 */
@ManagedBean
@RequestScoped
public class EventsDisplayBean implements Serializable {

    protected Event event;
    protected Contact contact;
    protected List<EventComment> comments;
    @ManagedProperty(value = "#{param['eventId']}")
    protected String eventId;
    @ManagedProperty(value = "#{param['contactId']}")
    protected String contactId;
    @ManagedProperty(value = "#{param['code']}")
    protected String code;
    @ManagedProperty(value = "#{registeredUserBean}")
    protected RegisteredUserBean rub;
    protected EventComment newComment;
    protected Integer rsvp;
    protected Invitation invitation;

    public EventsDisplayBean() {
    }

    @PostConstruct
    public void init() {
        //Fetch Event and contact from the given parameters
        EventManager em = new EventManager();
        ContactManager cm = new ContactManager();
        InvitationManager im = new InvitationManager();



        if (eventId != null) {
            event = em.findByID(Long.valueOf(eventId));
            //Check if the event viewed has passed
            em.checkStatusAndUpdateEvent(event);

            comments = event.getComments();
            if (comments == null) {
                comments = new ArrayList<EventComment>();
            }
        }
        if (contactId != null && code != null) {
            contact = cm.findByID(Long.valueOf(contactId));
            if (!code.equals(HashGenerator.generateHash(contact.getEmail()))) {
                contact = null;
            }
        }


        if (contactId != null && eventId != null && contact != null && event != null) {
            invitation = im.getInvitationForEvent(contact, event);
            if (invitation != null) {
                switch (invitation.getStatus()) {
                    case Pending:
                        invitation.setStatus(InvitationStatus.Viewed);
                        im.edit(invitation);
                        break;
                    case Attending:
                        rsvp = 1;
                        break;
                    case Not_Attending:
                        rsvp = 0;
                        break;
                }
            }
        }

        //HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        // rub = (RegisteredUserBean) session.getAttribute("registeredUserBean");

        System.out.println("Rub Logged In ; " + rub.loggedIn);
        if (rub != null && rub.loggedIn) {
            initialiseComment();
        }
    }

    private void initialiseComment() {
        newComment = new EventComment();
        newComment.setEvent(event);
        newComment.setRegisteredUser(rub.registeredUser);
    }

    public List<EventComment> getComments() {
        return comments;
    }

    public void setComments(List<EventComment> comments) {
        this.comments = comments;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public Event getEvent() {
        return event;
    }

    public void setEvent(Event event) {
        this.event = event;
    }

    public String getContactId() {
        return contactId;
    }

    public void setContactId(String contactId) {
        this.contactId = contactId;
    }

    public String getEventId() {
        return eventId;
    }

    public void setEventId(String eventId) {
        this.eventId = eventId;
    }

    public EventComment getNewComment() {
        return newComment;
    }

    public void setNewComment(EventComment newComment) {
        this.newComment = newComment;
    }

    public RegisteredUserBean getRub() {
        return rub;
    }

    public void setRub(RegisteredUserBean rub) {
        this.rub = rub;
    }

    public Integer getRsvp() {
        return rsvp;
    }

    public void setRsvp(Integer rsvp) {
        this.rsvp = rsvp;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void addCommentAction() {
        EventCommentManager ecm = new EventCommentManager();

        ecm.create(newComment);
        comments.add(newComment);

        initialiseComment();
    }

    public boolean getEventResponseTimePassed() {
        if (event == null || !event.getStatus().equals(EventStatus.Active)) {
            return true;
        }

        Date currentDate = Calendar.getInstance().getTime();
        Date referenceDate = null;

        if (event.getResponseTime() == null) {
            referenceDate = event.getStartTime();
        } else {
            referenceDate = event.getResponseTime();
        }

        return currentDate.after(referenceDate);
    }

    public void handleAttendance() {
        EventManager em = new EventManager();
        if (em.checkStatusAndUpdateEvent(event)) {
            InvitationManager im = new InvitationManager();
            invitation = im.findByID(invitation.getId());
            if (rsvp == 0) {
                invitation.setStatus(InvitationStatus.Not_Attending);
            } else if (rsvp == 1) {
                invitation.setStatus(InvitationStatus.Attending);
            }
            im.edit(invitation);
        }
    }

    public Invitation getInvitation() {
        return invitation;
    }

    public void setInvitation(Invitation invitation) {
        this.invitation = invitation;
    }

    public List<Invitation> getEventInvitations() {
        if (event == null) {
            return null;
        }
        InvitationManager inm = new InvitationManager();

        if (!rub.loggedIn) {
            return inm.getAnswerdInvitationsForEvent(event);
        }

        Long owner_id = event.getRegisteredUser().getId();
        Long user_id = rub.getRegisteredUser().getId();
        if (owner_id == user_id) {
            return inm.getInvitationsForEvent(event);
        } else {
            return inm.getAnswerdInvitationsForEvent(event);
        }

    }
}
